package com.example.controller;

import com.example.common.Result;
import com.example.entity.Grid;
import com.example.entity.GridType;
import com.example.service.GridReservationService;
import com.example.service.GridService;
import com.example.service.GridTypeService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * 网格的控制层
 **/
@RestController
@RequiredArgsConstructor
@RequestMapping("/grid")
public class GridController {

    private final GridService gridService;
    private final GridReservationService gridReservationService;
    private final GridTypeService gridTypeService;


    /**
     * 增
     **/
    @PostMapping("/add")
    public Result add(@RequestBody Grid grid) {
        gridService.add(grid);
        return Result.success();
    }

    /**
     * 删
     **/
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        gridService.deleteById(id);
        return Result.success();
    }

    /**
     * 批量删除
     **/
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        gridService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 改
     **/
    @PutMapping("/update")
    public Result updateById(@RequestBody Grid grid) {
        Grid grid1 = gridService.selectById(grid.getId());
        GridType type = gridTypeService.selectById(grid1.getTypeId());
        System.out.println(type.toString());
        if (type.getType().equals("座位") &&
                gridReservationService.selectByGId(grid.getId())
        ) {
            return Result.error("该座位正在被预约,无法修改！");
        }
        gridService.updateById(grid);
        return Result.success();
    }

    /**
     * 根据ID查询
     **/
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Grid grid = gridService.selectById(id);
        return Result.success(grid);
    }

    /**
     * 查询所有
     **/
    @GetMapping("/selectAll")
    public Result selectAll(Grid grid) {
        List<Grid> list = gridService.selectAll(grid);
        return Result.success(list);
    }

    /**
     * 分页查询
     **/
    @GetMapping("/selectPage")
    public Result selectPage(Grid grid,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Grid> page = gridService.selectPage(grid, pageNum, pageSize);
        return Result.success(page);
    }

}